import * as THREE from 'three';
import TWEEN from '../../../node_modules/three/examples/jsm/libs/tween.module.js';
import boxImg from '../../textures/crate.gif'

//绘制一个箱子

class showBox{
    constructor(scene,x,y,boxSize){
        this.scene = scene;
        this.opacity={v:0}; // 初始透明度为0
        this.x=x;
        this.y=y;
        this.newPos={x:x,y:y}//移动目标位置
        this.createBox();
    }
    createBox(){
        const texture = new THREE.TextureLoader().load( boxImg );
		    texture.colorSpace = THREE.SRGBColorSpace;

		    const geometry = new THREE.BoxGeometry(60,60,60);
		    this.boxMaterial = new THREE.MeshBasicMaterial( { map: texture } );

        this.mesh = new THREE.Mesh( geometry, this.boxMaterial );
        this.boxMaterial.transparent=true;
        this.boxMaterial.opacity=0;//刚加载时不显示，要显示时调用fadeIn
        this.mesh.position.x=this.x;
        this.mesh.position.y=this.y;
        this.mesh.position.z=0;
        this.scene.add( this.mesh );

    }

    fadeIn(callBack){
        new TWEEN.Tween(this.opacity)
        .to( {v:1} , 2000) // 2秒内透明度从0变为1
        .onUpdate(() => {
            this.boxMaterial.opacity = this.opacity.v; // 更新材质透明度
        })
        .onComplete(() => {
          if(callBack){callBack();}
        })
        .start();
    }

    fadeOut(callBack){
        new TWEEN.Tween(this.opacity)
        .to( {v:0} , 2000) // 2秒内透明度从0变为1
        .onUpdate(() => {
            this.boxMaterial.opacity = this.opacity.v; // 更新材质透明度
        })
        .onComplete(() => {
          if(callBack){callBack();}
        })
        .start();
    }

  //移动
  moveTo(tox,toy,callBack){
    console.log('box move to',tox, toy)
    new TWEEN.Tween(this.newPos)
    .to( {x:tox,y:toy} , 2000) 
    .onUpdate(() => {
      //console.log(this.newPos.x, this.newPos.y)
      this.x = this.newPos.x
      this.y = this.newPos.y
      this.mesh.position.x=this.x;
      this.mesh.position.y=this.y;
    })
    .onComplete(() => {
      console.log('box move to complete',callBack)
      if(callBack){callBack();}
    })
    .start();
  }

}

export default showBox;